﻿using System;
using System.Collections.Generic;
using System.Linq;
using HtmlAgilityPack;
using QNUnit.Core.Info;
using WatiN.Core;

namespace QNUnit.Core
{
    public class Watin
    {
        #region Fields

        private readonly Browser _browser;

        #endregion

        #region Constructors

        public Watin(Browser browser)
        {
            _browser = browser;
        }

        #endregion

        #region Public

        public string GetTestGroupName()
        {
            var testName = _browser.Div(Find.ById("test-group-name")).InnerHtml;
            return testName;
        }

        public List<QUnitTest> GetTests()
        {
            var bodyHtml = new HtmlDocument();
            bodyHtml.LoadHtml(_browser.Html);

            var testsHtml = bodyHtml.DocumentNode.SelectNodes("//ol[@id='qunit-tests']/li");
            var tests = new List<QUnitTest>();

            foreach (var testHtml in testsHtml)
            {
                var testName = testHtml.SelectSingleNode(".//span[@class='test-name']").InnerHtml;
                var test = string.Compare(testHtml.Attributes["class"].Value, "pass") == 0 ? new QUnitTest(testName, true) : new QUnitTest(testName, false);

                var subTestsHtml = testHtml.SelectNodes(".//ol/li");

                foreach (var subTestHtml in subTestsHtml)
                {
                    var hasPassed = string.Compare(subTestHtml.Attributes["class"].Value, "pass") == 0;

                    var message = subTestHtml.SelectSingleNode("./span[@class='test-message']");
                    var expected = subTestHtml.SelectSingleNode("./span[@class='test-expected']");
                    var actual = subTestHtml.SelectSingleNode("./span[@class='test-actual']");

                    if (message == null)
                    {
                        // qunit "ok" test does not have a message
                        test.SubTests.Add(new QUnitSubTest(hasPassed, subTestHtml.InnerHtml));
                    }
                    else
                    {
                        test.SubTests.Add(hasPassed
                                          ? new QUnitSubTest(message.InnerHtml, expected.InnerHtml)
                                          : new QUnitSubTest(message.InnerHtml, expected.InnerHtml, actual.InnerHtml));
                    }
                }

                tests.Add(test);
            }

            return tests;
        }

        #endregion
    }
}
